package service

import (
	"context"
	"qld2devservice/proto"
	"qld2devservice/utils"

	"google.golang.org/grpc"
)

const (
	ADDRESS_SOC = "qld2socserver:8119"
)

//var (
//	socLiNMC     = []float64{0, 0.0250007, 0.0500006, 0.1, 0.200001, 0.300001, 0.400001, 0.500001, 0.600001, 0.7, 0.800001, 0.900001, 1}
//	voltageLiNMC = []float64{41.4863, 43.201, 44.2917, 45.3384, 45.8822, 46.5316, 47.4106, 48.1257, 48.7384, 49.6384, 51.0165, 52.6378, 54}
//)

//func calculateSocByVoltage(voltage float64) (soc float64) {
//	if voltage < voltageLiNMC[0] {
//		return 0
//	}
//	if voltage >= voltageLiNMC[len(voltageLiNMC)-1] {
//		return 1
//	}
//	for i := 1; i < len(voltageLiNMC); i++ {
//		if voltage < voltageLiNMC[i] {
//			soc = socLiNMC[i-1] + (voltage-voltageLiNMC[i-1])*(socLiNMC[i]-socLiNMC[i-1])/(voltageLiNMC[i]-voltageLiNMC[i-1])
//			break
//		}
//	}
//	return soc
//}

func SetUserDataEnd(current float32, userID, orderID string, timegap int32) (response string, err error) {
	// 连接到 gRPC 服务器
	conn, err := grpc.Dial(ADDRESS_SOC, grpc.WithInsecure())
	if err != nil {
		errNew := utils.WrapError(err, "SetUserDataEnd:1 ,gRPC服务器连接失败")
		utils.MyPrint(utils.PRINT_ERROR, errNew.Msg())
		return "", errNew
	}
	defer conn.Close()

	// 初始化 gRPC 客户端
	client := proto.NewSOCUserServiceClient(conn)
	res := proto.UserSOCData{In: current, UserID: userID, OrderID: orderID, Timegap: timegap}
	utils.MyPrint(utils.PRINT_INFO, "SetUserDataEnd request", res)
	resp, err := client.SetUserDataEnd(context.Background(), &res)
	if err != nil {
		errNew := utils.WrapError(err, "SetUserDataEnd:2 ,gRPC调用失败")
		utils.MyPrint(utils.PRINT_ERROR, errNew.Msg())
		return "", errNew
	}
	utils.MyPrint(utils.PRINT_INFO, "SetUserDataEnd response", utils.TransProtoToJson(resp))
	return resp.Text, nil
}

func GetSOCValue(current, volt, in float32, userID, orderID string, timegap int32, batteryType int64) (Soc, Dsoc float32, Timeleft int32, err error) {
	// 连接到 gRPC 服务器
	conn, err := grpc.Dial(ADDRESS_SOC, grpc.WithInsecure())
	if err != nil {
		errNew := utils.WrapError(err, "GetSOCValue:1 ,gRPC服务器连接失败")
		utils.MyPrint(utils.PRINT_ERROR, errNew.Msg())
		return -1, 0, 0, errNew
	}
	defer conn.Close()

	// 初始化 gRPC 客户端
	client := proto.NewSOCUserServiceClient(conn)
	res := proto.SOCRequestCurrentPara{
		In:          in,
		UserID:      userID,
		OrderID:     orderID,
		Timegap:     timegap,
		Current:     current,
		Volt:        volt,
		BatteryType: batteryType,
	}
	utils.MyPrint(utils.PRINT_INFO, "GetSOCValue request", res)
	resp, err := client.GetSOCValue(context.Background(), &res)
	if err != nil {
		errNew := utils.WrapError(err, "GetSOCValue:2 ,gRPC调用失败")
		utils.MyPrint(utils.PRINT_ERROR, errNew.Msg())
		return -1, 0, 0, errNew
	}
	utils.MyPrint(utils.PRINT_INFO, "GetSOCValue response", utils.TransProtoToJson(resp))
	return resp.Soc, resp.Dsoc, resp.Timeleft, nil
}
